<?php


namespace App\Models\CacheModel;


use App\Models\Api\BaseCache;
use think\Log;
use AstroTool\Cache\CacheManage;

class ZlPosterShareActiveZanRecord extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zl_poster_share_active_zan_record';

    protected $cacheModel = 'fortune.poster_share_active';

    /**
     * 投票
     * @param $uid
     * @param $posterId
     * @return bool
     */
    public function zan($uid, $posterId)
    {
        try
        {
            $data = [
                'uid' => $uid,
                'poster_id' => $posterId,
                'create_time' => time(),
            ];

            $this->insert($data);

            CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('zan_record', $uid)
                ->listAdd([$posterId => $data['create_time']], 0, 'zan_record');
            return true;
        }
        catch (\Exception $e)
        {
            Log::write("海报分享活动 投票失败：{$e->getMessage()};File:{$e->getFile()};Line:{$e->getLine()}", 'error', true);
            return false;
        }
    }

    /**
     * 取消投票
     * @param $uid
     * @param $posterId
     * @return false
     */
    public function cancelZan($uid, $posterId)
    {
        try
        {
            $this->where(['uid' => $uid, 'poster_id' => $posterId])->delete();

            CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('zan_record', $uid)
                ->delJudge([$posterId], 'zan_record');

            return true;
        }
        catch (\Exception $e)
        {
            Log::write("海报分享活动 取消投票失败：{$e->getMessage()};File:{$e->getFile()};Line:{$e->getLine()}", 'error', true);
            return false;
        }
    }

    /**
     * 获取用户点赞的
     */
    public function getZanPosterIds($uid)
    {
        $posterPageIds = CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel)
            ->setCacheKeyDetail('zan_record', $uid)
            ->setPage(-1)
            ->setSort('desc')
            ->getListPageDataIds(function ($isCache = true, $sortType = 'desc') use ($uid)
            {
                try
                {
                    $data = $this->alias('z')->join('wechat_backup_07_18_14_43_00.zl_poster_share_active a', 'a.id=z.poster_id')
                        ->where(['z.uid' => $uid, 'a.status' => 1, 'a.delete_time' => null])->column('z.create_time', 'z.poster_id');

                    $resData = [];
                    foreach ($data as $posterId => $createTime)
                    {
                        $resData[$posterId] = ['create_time' => $createTime];
                    }

                    return $resData;
                }
                catch (\Exception $e)
                {
                    return [];
                }
            }, 'create_time', 0, 'zan_record');

        return $posterPageIds['data'];
    }

    /**
     * 获取投票记录
     * @param $uid
     * @param $week
     * @param $page
     * @return array|mixed
     * @throws \Exception
     */
    public function getZanRecord($uid, $week, $page)
    {
        $posterPageData = CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel)
            ->setCacheKeyDetail('zan_record', $uid)
            ->setPage($page)
            ->setPageSize(10)
            ->setSort('desc')
            ->getListPageDataIds(function ($isCache = true, $sortType = 'desc') use ($uid)
            {
                try
                {
                    $data = $this->alias('z')->join('wechat_backup_07_18_14_43_00.zl_poster_share_active a', 'a.id=z.poster_id')
                        ->where(['z.uid' => $uid, 'a.status' => 1, 'a.delete_time' => null])->column('z.create_time', 'z.poster_id');

                    $resData = [];
                    foreach ($data as $posterId => $createTime)
                    {
                        $resData[$posterId] = ['create_time' => $createTime];
                    }

                    return $resData;
                }
                catch (\Exception $e)
                {
                    return [];
                }
            }, 'create_time', 0, 'zan_record');

        $posterIds = array_keys($posterPageData['data']);

        $posterInfoList = (new ZlPosterShareActive())->batchGetInfoByIds($posterIds);

        $resData = [];
        $rankingIndexDatas = (new ZlPosterShareActive())->getRankingIndex($week);
        foreach ($posterIds as $posterIdItem)
        {
            if (!isset($posterInfoList[$posterIdItem]) || (int)$posterInfoList[$posterIdItem]['status'] !== 1)
            {   // 列表缓存 数据异常
                CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('zan_record', $uid)->rmCache('zan_record');
                continue;
            }

            // $zanStr = $posterInfoList[$posterIdItem]['zan'] >= 1000 ? sprintf('%.1fk', $posterInfoList[$posterIdItem]['zan'] / 1000) : $posterInfoList[$posterIdItem]['zan'];

            if ($week === (int)$posterInfoList[$posterIdItem]['week'])
            {
                $rankingDesc = $rankingIndexDatas[$posterIdItem]['ranking_index'] > 100 ? '未进前100名' : "当前第{$rankingIndexDatas[$posterIdItem]['ranking_index']}名";
            } else
            {
                $rankingDesc = $posterInfoList[$posterIdItem]['ranking'] > 100 ? '未进前100名' : "第{$posterInfoList[$posterIdItem]['ranking']}名";
            }

            $resData[] = [
                'id' => (int)$posterIdItem,
                'poster_url' => $posterInfoList[$posterIdItem]['poster'],
                'nickname' => $posterInfoList[$posterIdItem]['nickname'],
                'avatar' => $posterInfoList[$posterIdItem]['avatar'],
                'zan_num' => $posterInfoList[$posterIdItem]['zan'],
                'ranking_desc' => $rankingDesc,
            ];
        }

        $posterPageData['data'] = $resData;

        return $posterPageData;
    }
}
